package com.example.opengldemo._camera_demo.renderer;

import android.graphics.Bitmap;
import android.opengl.GLES30;
import android.opengl.GLUtils;
import android.util.Log;

import com.example.opengldemo.util.TextureUtil;

public class WaterMarkFilter extends LazyFilter {
    private int[] viewPort=new int[4];
    private int[] markPort=new int[4];
    private final LazyFilter mark=new LazyFilter(){

        @Override
        protected void onClear() {

        }
    };
    private int markTextureId=-1;
    public WaterMarkFilter setMarkPosition(final int x, final int y, final int width, final int height){
        markPort[0]=x;
        markPort[1]=y;
        markPort[2]=width;
        markPort[3]=height;
        runOnGLThread(new Runnable() {
            @Override
            public void run() {
                mark.sizeChanged(width, height);
            }
        });
        return this;
    }

    public WaterMarkFilter setMark(final Bitmap bmp){
        runOnGLThread(new Runnable() {
            @Override
            public void run() {
                Log.e("WaterMarkFilter"  , "setMark 1 " );
                if(bmp!=null){
                    Log.e("WaterMarkFilter"  , "setMark 2 " );
                    if(markTextureId==-1){
                        Log.e("WaterMarkFilter"  , "setMark 31 " );
                        markTextureId= TextureUtil.createTextureID(false);
                    }else{
                        Log.e("WaterMarkFilter"  , "setMark 32 " );
                        GLES30.glBindTexture(GLES30.GL_TEXTURE_2D,markTextureId);
                    }
                    GLUtils.texImage2D(GLES30.GL_TEXTURE_2D,0,bmp,0);
                    bmp.recycle();
                }else{
                    Log.e("WaterMarkFilter"  , "setMark 21 " );
                    if(markTextureId!=-1){
                        Log.e("WaterMarkFilter"  , "setMark 4 " );
                        GLES30.glDeleteTextures(1,new int[]{markTextureId},0);
                    }
                }
            }
        });
        return this;
    }

    @Override
    protected void onCreate() {
        super.onCreate();
        mark.create();
    }

    @Override
    protected void onDraw() {
        //todo change blend and viewport
        super.onDraw();
        Log.e("WaterMarkFiltee"  , "onDraw 1 " );
        if(markTextureId!=-1){
            Log.e("WaterMarkFiltee"  , "onDraw 2 " );
            GLES30.glGetIntegerv(GLES30.GL_VIEWPORT,viewPort,0);
            GLES30.glViewport(markPort[0],mHeight-markPort[3]-markPort[1],markPort[2],markPort[3]);

            GLES30.glEnable(GLES30.GL_BLEND);
            GLES30.glBlendFunc(GLES30.GL_SRC_ALPHA,GLES30.GL_ONE_MINUS_SRC_ALPHA);
            GLES30.glBlendEquation(GLES30.GL_FUNC_ADD);
            mark.draw(markTextureId);
            GLES30.glDisable(GLES30.GL_BLEND);

            GLES30.glViewport(viewPort[0],viewPort[1],viewPort[2],viewPort[3]);
        }
        //todo reset blend and view port
    }
}
